package {
	import flash.display.Loader;	
	import flash.display.Bitmap;	
	import flash.events.MouseEvent;	
	import flash.events.Event;	
	import flash.display.DisplayObject;	
	import flash.display.Sprite;
	
	/**
	 * @author Max_Andresen
	 */
	public class Gallery extends Sprite {
		
		//create a bitmap that will be the main image once you click on its thumb
		private var currentImage:Bitmap = new Bitmap();
		//create an instance of the GalleryImage Class
		private var galleryImage:GalleryImage;
		//create an array to hold your image urls
		private var images:Array = new Array(
		"images/1.jpg",
		"images/2.jpg",
		"images/3.jpg",
		"images/4.jpg",
		"images/5.jpg",
		"images/6.jpg");


		public function Gallery() {
			//add the main image to the stage 
			//*it will currently be empty but we add it here so we can change
			//   its content later and have it be automatically updated
			addChild(currentImage);
			//setting x and y on where you would like the main image
			currentImage.x = 150;
			currentImage.y = 50;
			//create a loop to iterate through your array of urls and passing the url into the GalleryImage constructor
			//these will be your thumbs
			for (var i : int = 0; i < images.length; i++) {
				//create a new Loading instance and pass in the required parameters
				var thisLoader : Loading = new Loading(100, 100, 0x000000, "Loading...", 0xffffff);
				//create a new display object that adds a new GalleryImage and pass is the required parameters along with the Loading instance
				var thisImage:GalleryImage = addChild(new GalleryImage(images[i], 100, 100, thisLoader)) as GalleryImage;	
				//setting x or y on this will determine where your thumbs are placed
				thisImage.y = i * 100;
				//adding a click handler for each thumb
				thisImage.addEventListener(MouseEvent.CLICK, onClickThumb);
				//to have the first image be visible when the loading is complete
				// check to see if i is 0 because if its not it means you have click something
				if(i == 0) {
					//add an event listener to the imageLoaded being added
					thisImage.imageLoader.addEventListener(Event.ADDED, onFirstThumbLoaded);
				}
			}
		}
		//this function sets galleryImage to the first image
		//  then it sets the current image to be the first image
		private function onFirstThumbLoaded(event:Event):void {
			galleryImage = (event.currentTarget as Loader).content.parent as GalleryImage;
			currentImage.bitmapData = galleryImage.image.bitmapData;
		}
		private function onClickThumb(event:MouseEvent):void {
			//cast the galleryImage var as the selected thumb content 
			galleryImage = event.currentTarget as GalleryImage;
			//set the main image to be the clicked thumbnails unscaled image
			currentImage.bitmapData = galleryImage.image.bitmapData;
		}
	}
}
